<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

class ActiveReport extends Backend
{
    protected $model = null;
    protected $noNeedRight = ['index'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('ActiveReport');
    }

    /**
     * 主动报工列表
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $list = $this->model
                ->alias('ar')
                ->join('scanwork_order o', 'ar.order_id = o.id')
                ->join('scanwork_model m', 'ar.model_id = m.id')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->join('user u', 'ar.user_id = u.id')
                ->field('ar.*, o.order_no, p.name as product_name, m.name as model_name, u.nickname as user_name')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
                
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核主动报工
     */
    public function audit()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数错误');
        }
        
        $activeReport = $this->model
            ->alias('ar')
            ->join('scanwork_order o', 'ar.order_id = o.id')
            ->join('scanwork_model m', 'ar.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('user u', 'ar.user_id = u.id')
            ->field('ar.*, o.order_no, p.name as product_name, m.name as model_name, u.nickname as user_name')
            ->where('ar.id', $id)
            ->find();
            
        if (!$activeReport) {
            $this->error('报工记录不存在');
        }
        
        // 获取员工上传的图片（旧表）
        $workerImages = Db::name('scanwork_active_report_image')
            ->where('active_report_id', $id)
            ->where('image_type', 1)
            ->select();
            
        // 获取管理员验货图片（旧表）
        $auditImages = Db::name('scanwork_active_report_image')
            ->where('active_report_id', $id)
            ->where('image_type', 2)
            ->select();
            
        // 获取产品编号图片（新表）
        $productItemImages = Db::name('scanwork_active_report_product_item')
            ->where('active_report_id', $id)
            ->field('item_no, image_url')
            ->select();
            
        // 按产品编号分组图片
        $groupedProductImages = [];
        foreach ($productItemImages as $item) {
            $itemNo = $item['item_no'];
            if (!isset($groupedProductImages[$itemNo])) {
                $groupedProductImages[$itemNo] = [];
            }
            $groupedProductImages[$itemNo][] = $item['image_url'];
        }
            
        $this->view->assign([
            'activeReport' => $activeReport,
            'workerImages' => $workerImages,
            'auditImages' => $auditImages,
            'productItemImages' => $groupedProductImages
        ]);
        
        return $this->view->fetch();
    }

    /**
     * 提交审核
     */
    public function submitAudit()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            // 添加详细的调试日志
            trace('=== 审核提交开始 ===', 'debug');
            trace('POST参数: ' . json_encode($params, JSON_UNESCAPED_UNICODE), 'debug');
            trace('FILES参数: ' . json_encode($_FILES, JSON_UNESCAPED_UNICODE), 'debug');
            trace('当前用户ID: ' . $this->auth->id, 'debug');
            
            try {
                Db::startTrans();
                
                $id = intval($params['id'] ?? 0);
                $status = intval($params['status'] ?? 0);
                $auditReason = $params['audit_reason'] ?? '';
                
                trace('解析参数 - ID: ' . $id . ', 状态: ' . $status . ', 原因: ' . $auditReason, 'debug');
                
                // 验证必填参数
                if (!$id) {
                    trace('错误：缺少报工记录ID', 'error');
                    throw new \Exception('缺少报工记录ID');
                }
                if (!$status || !in_array($status, [1, 2])) {
                    trace('错误：无效的审核状态 - ' . $status, 'error');
                    throw new \Exception('请选择审核结果（通过或拒绝）');
                }
                
                // 获取报工记录
                $activeReport = $this->model->where('id', $id)->find();
                trace('查询报工记录结果: ' . json_encode($activeReport, JSON_UNESCAPED_UNICODE), 'debug');
                
                if (!$activeReport) {
                    trace('错误：报工记录不存在 - ID: ' . $id, 'error');
                    throw new \Exception('报工记录不存在');
                }
                
                // 检查是否已经审核过
                if ($activeReport['status'] != 0) {
                    trace('错误：记录已审核过 - 当前状态: ' . $activeReport['status'], 'error');
                    throw new \Exception('该记录已经审核过了');
                }
                
                // 更新报工记录
                $updateData = [
                    'status' => $status,
                    'audit_reason' => $auditReason,
                    'audit_user_id' => $this->auth->id,
                    'audit_time' => time(),
                    'updatetime' => time()
                ];
                
                // 如果审核通过，保持原有工资
                if ($status == 1) {
                    // 审核通过，保持原有的工资计算
                    $updateData['piece_wage'] = $activeReport['piece_wage'];
                    $updateData['time_wage'] = $activeReport['time_wage'];
                    $updateData['total_wage'] = $activeReport['total_wage'];
                } else {
                    // 审核拒绝，工资清零
                    $updateData['piece_wage'] = 0;
                    $updateData['time_wage'] = 0;
                    $updateData['total_wage'] = 0;
                    
                    // 删除产品编号图片记录，让员工可以重新提交
                    $productItemImages = Db::name('scanwork_active_report_product_item')
                        ->where('active_report_id', $id)
                        ->select();
                    
                    foreach ($productItemImages as $item) {
                        try {
                            // 如果有云存储文件ID，删除云存储文件
                            if (!empty($item['cloud_file_id'])) {
                                $cloudService = new \app\common\service\ScanworkCloudService();
                                $cloudService->deleteFile($item['cloud_file_id']);
                            } else {
                                // 删除本地文件
                                $filePath = ROOT_PATH . 'public' . $item['image_url'];
                                if (file_exists($filePath)) {
                                    unlink($filePath);
                                }
                            }
                        } catch (Exception $e) {
                            // 记录错误但继续删除其他文件
                            error_log('删除产品图片失败：' . $e->getMessage());
                        }
                    }
                    
                    // 删除数据库记录
                    Db::name('scanwork_active_report_product_item')
                        ->where('active_report_id', $id)
                        ->delete();
                }
                
                $result = $this->model->where('id', $id)->update($updateData);
                trace('更新结果: ' . $result, 'debug');
                
                // 处理验货图片上传
                if (isset($_FILES['audit_images']) && !empty($_FILES['audit_images']['name'][0])) {
                    $cloudService = new \app\common\service\ScanworkCloudService();
                    $count = 0;
                    
                    foreach ($_FILES['audit_images']['tmp_name'] as $k => $tmp) {
                        if ($_FILES['audit_images']['error'][$k] == 0) {
                            if ($count >= 9) break; // 最多9张图片
                            
                            // 构建文件数组
                            $file = [
                                'name' => $_FILES['audit_images']['name'][$k],
                                'type' => $_FILES['audit_images']['type'][$k],
                                'tmp_name' => $_FILES['audit_images']['tmp_name'][$k],
                                'error' => $_FILES['audit_images']['error'][$k],
                                'size' => $_FILES['audit_images']['size'][$k]
                            ];
                            
                            // 上传到云存储
                            $result = $cloudService->uploadActiveReportImage($file);
                            
                            if ($result['success']) {
                                Db::name('scanwork_active_report_image')->insert([
                                    'active_report_id' => $id,
                                    'image_url' => $result['url'],
                                    'cloud_file_id' => $result['file_id'], // 保存云存储文件ID
                                    'image_type' => 2, // 管理员验货图片
                                    'createtime' => time()
                                ]);
                                $count++;
                            }
                        }
                    }
                }
                
                Db::commit();
                trace('审核完成，ID: ' . $id . ', 状态: ' . $status, 'debug');
                
                // 明确返回JSON格式
                return json(['code' => 1, 'msg' => '审核完成']);
                
            } catch (\Exception $e) {
                Db::rollback();
                trace('审核失败: ' . $e->getMessage(), 'error');
                
                // 明确返回JSON格式
                return json(['code' => 0, 'msg' => '审核失败：' . $e->getMessage()]);
            }
        }
    }

    /**
     * 删除主动报工
     */
    public function del($ids = null)
    {
        if (!$ids) {
            $ids = $this->request->get('ids');
        }
        if (!$ids) {
            $this->error('参数错误');
        }
        
        try {
            Db::startTrans();
            
            $idArray = explode(',', $ids);
            foreach ($idArray as $id) {
                // 删除图片
                $images = Db::name('scanwork_active_report_image')
                    ->where('active_report_id', $id)
                    ->select();
                    
                foreach ($images as $image) {
                    try {
                        // 如果有云存储文件ID，删除云存储文件
                        if (!empty($image['cloud_file_id'])) {
                            $cloudService = new \app\common\service\ScanworkCloudService();
                            $cloudService->deleteFile($image['cloud_file_id']);
                        } else {
                            // 删除本地文件
                            $filePath = ROOT_PATH . 'public' . $image['image_url'];
                            if (file_exists($filePath)) {
                                unlink($filePath);
                            }
                        }
                    } catch (Exception $e) {
                        // 记录错误但继续删除其他文件
                        error_log('删除图片失败：' . $e->getMessage());
                    }
                }
                
                Db::name('scanwork_active_report_image')
                    ->where('active_report_id', $id)
                    ->delete();
                    
                // 删除报工记录
                $this->model->where('id', $id)->delete();
            }
            
            Db::commit();
            $this->success('删除成功');
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 查看报工详情
     */
    public function detail()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数错误');
        }
        
        // 获取报工详情
        $activeReport = Db::name('scanwork_active_report')
            ->alias('ar')
            ->join('scanwork_order o', 'ar.order_id = o.id')
            ->join('scanwork_model m', 'ar.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'ar.process_id = pr.id')
            ->join('user u', 'ar.user_id = u.id')
            ->field('ar.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name, u.nickname as user_name')
            ->where('ar.id', $id)
            ->find();
            
        if (!$activeReport) {
            $this->error('报工记录不存在');
        }
        
        // 获取员工上传的图片（旧表）
        $workerImages = Db::name('scanwork_active_report_image')
            ->where('active_report_id', $id)
            ->where('image_type', 1)
            ->select();
            
        // 获取管理员验货图片（旧表）
        $auditImages = Db::name('scanwork_active_report_image')
            ->where('active_report_id', $id)
            ->where('image_type', 2)
            ->select();
            
        // 获取产品编号图片（新表）
        $productItemImages = Db::name('scanwork_active_report_product_item')
            ->where('active_report_id', $id)
            ->field('item_no, image_url')
            ->select();
            
        // 按产品编号分组图片
        $groupedProductImages = [];
        foreach ($productItemImages as $item) {
            $itemNo = $item['item_no'];
            if (!isset($groupedProductImages[$itemNo])) {
                $groupedProductImages[$itemNo] = [];
            }
            $groupedProductImages[$itemNo][] = $item['image_url'];
        }
            
        // 获取审核人信息
        $auditUser = null;
        if ($activeReport['audit_user_id']) {
            $auditUser = Db::name('user')
                ->where('id', $activeReport['audit_user_id'])
                ->field('nickname')
                ->find();
        }
        
        $this->view->assign([
            'activeReport' => $activeReport,
            'workerImages' => $workerImages,
            'auditImages' => $auditImages,
            'productItemImages' => $groupedProductImages,
            'auditUser' => $auditUser
        ]);
        
        return $this->view->fetch();
    }

    /**
     * 批量审核
     */
    public function batchAudit()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            try {
                Db::startTrans();
                
                $ids = $params['ids'];
                $status = intval($params['status']);
                $auditReason = $params['audit_reason'] ?? '';
                
                if (!$ids) {
                    throw new Exception('请选择要审核的记录');
                }
                
                $idArray = explode(',', $ids);
                
                // 更新报工记录
                $updateData = [
                    'status' => $status,
                    'audit_reason' => $auditReason,
                    'audit_user_id' => $this->auth->id,
                    'audit_time' => time(),
                    'updatetime' => time()
                ];
                
                $this->model->where('id', 'in', $idArray)->update($updateData);
                
                Db::commit();
                $this->success('批量审核完成');
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('批量审核失败：' . $e->getMessage());
            }
        }
        
        $this->error('请求方式错误');
    }

    /**
     * 获取选中记录信息
     */
    public function getSelectedRecords()
    {
        $ids = $this->request->get('ids');
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $idArray = explode(',', $ids);
        
        $records = $this->model
            ->alias('ar')
            ->join('scanwork_order o', 'ar.order_id = o.id')
            ->join('scanwork_model m', 'ar.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('user u', 'ar.user_id = u.id')
            ->where('ar.id', 'in', $idArray)
            ->field('ar.id, o.order_no, p.name as product_name, m.name as model_name, u.nickname as user_name, ar.quantity')
            ->select();
            
        $this->success('获取成功', $records);
    }

    /**
     * 统计报表
     */
    public function statistics()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->get();
            $startDate = $params['start_date'] ?? date('Y-m-01');
            $endDate = $params['end_date'] ?? date('Y-m-d');
            $userId = $params['user_id'] ?? '';
            $status = $params['status'] ?? '';
            
            $where = [
                'ar.work_date' => ['between', [$startDate, $endDate]]
            ];
            
            if ($userId) {
                $where['ar.user_id'] = $userId;
            }
            
            if ($status !== '') {
                $where['ar.status'] = $status;
            }
            
            // 按员工统计
            $userStats = Db::name('scanwork_active_report')
                ->alias('ar')
                ->join('user u', 'ar.user_id = u.id')
                ->where($where)
                ->field('u.nickname as user_name, COUNT(*) as report_count, SUM(ar.quantity) as total_quantity, SUM(ar.total_wage) as total_wage')
                ->group('ar.user_id')
                ->select();
                
            // 按产品统计
            $productStats = Db::name('scanwork_active_report')
                ->alias('ar')
                ->join('scanwork_model m', 'ar.model_id = m.id')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->where($where)
                ->field('p.name as product_name, m.name as model_name, COUNT(*) as report_count, SUM(ar.quantity) as total_quantity, SUM(ar.total_wage) as total_wage')
                ->group('ar.model_id')
                ->select();
                
            // 按状态统计
            $statusStats = Db::name('scanwork_active_report')
                ->alias('ar')
                ->where($where)
                ->field('ar.status, COUNT(*) as count')
                ->group('ar.status')
                ->select();
                
            // 按日期统计
            $dateStats = Db::name('scanwork_active_report')
                ->alias('ar')
                ->where($where)
                ->field('ar.work_date, COUNT(*) as report_count, SUM(ar.quantity) as total_quantity, SUM(ar.total_wage) as total_wage')
                ->group('ar.work_date')
                ->order('ar.work_date')
                ->select();
                
            return json([
                'code' => 1,
                'data' => [
                    'user_stats' => $userStats,
                    'product_stats' => $productStats,
                    'status_stats' => $statusStats,
                    'date_stats' => $dateStats
                ]
            ]);
        }
        
        // 获取员工列表
        $users = Db::name('user')
            ->where('status', 'normal')
            ->field('id, nickname')
            ->select();
            
        $this->view->assign('users', $users);
        return $this->view->fetch();
    }
} 